using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace AirConnon
{
    public class PlayerCharacter : MonoBehaviour
    {
        private Rigidbody characterRigidbody;
        private Animator animator;
        private Vector3 moveVelocity;
        private bool isGrounded;
        private bool jumping;
        private bool falling;

        public float speed;
        public Vector3 jumpForce;
        public AirCannonWeapon airCannonWeapon;
        public float jumpSpeed;

        private void Start()
        {
            characterRigidbody = GetComponentInChildren<Rigidbody>();
            animator = GetComponentInChildren<Animator>();
            airCannonWeapon = GetComponentInChildren<AirCannonWeapon>();

            jumpForce = new Vector3(0, 200, 0);
            jumpSpeed = 8;
        }


        // Update is called once per frame
        private void Update()
        {
            characterRigidbody.velocity = moveVelocity;
            if (moveVelocity.x == 0 && moveVelocity.z == 0)
            {
                animator.SetBool("Running", false);
            }
            if (isGrounded)
            {
                jumping = false;
                falling = false;
            }
            else if (characterRigidbody.velocity.y < 0)
            {
                falling = true;
            }
        }

        private void FixedUpdate()
        {
            GroundDetect();
        }

        private void GroundDetect()
        {
            Vector3 rayOriginPos = transform.position;
            Debug.DrawLine(rayOriginPos, new Vector3(rayOriginPos.x, rayOriginPos.y - 0.5f, rayOriginPos.z), Color.red);

            RaycastHit hit;
            if (Physics.Raycast(rayOriginPos, -transform.up, out hit, 0.5f))
            {
                animator.SetBool("isGrounded", true);
                isGrounded = true;
            }
            else
            {
                animator.SetBool("isGrounded", false);
                isGrounded = false;
            }
        }

        public void Move(float xSpeed, float zSpeed)
        {
            animator.SetBool("Running", true);
            moveVelocity.x = xSpeed * speed;
            moveVelocity.z = zSpeed * speed;

            float blend = Mathf.Abs(xSpeed) > Mathf.Abs(zSpeed) ? Mathf.Abs(xSpeed) : Mathf.Abs(zSpeed);
        }

        public void Move(Vector3 direction, float speed)
        {
            direction = direction.normalized;

            moveVelocity = new Vector3(direction.x * speed, moveVelocity.y, direction.z * speed);
            direction = new Vector3(-direction.z, 0, direction.x);
        }

        public void Jump(float speed)
        {
            if (!jumping)
            {
                animator.SetTrigger("Jump");
                jumping = true;
                moveVelocity.y = 0;
                moveVelocity.y = speed;
            }
        }
    }

}

